package com.sysd.imgboard.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
import org.slim3.controller.Controller;
import org.slim3.controller.Navigation;
import org.slim3.datastore.Datastore;

import com.sysd.imgboard.constant.AppConst;
import com.sysd.imgboard.constant.SessionConst;
import com.sysd.imgboard.meta.ChildMeta;
import com.sysd.imgboard.meta.ImageMeta;
import com.sysd.imgboard.meta.ThreadMeta;
import com.sysd.imgboard.model.Child;
import com.sysd.imgboard.model.Image;
import com.sysd.imgboard.model.Session;
import com.sysd.imgboard.model.Thread;
import com.sysd.imgboard.service.user.IndexService;
import com.sysd.imgboard.util.ForwardUtil;

public class IndexController extends Controller {

    @SuppressWarnings("unused")
    private static final Logger logger = Logger.getLogger(IndexController.class.getName());

    private Integer count = 0;
    
    @Override
    public Navigation run() {
        
        Session s = sessionScope(SessionConst.USER_SESSION_KEY());
        
        Integer page = requestScope("p");
        if(page == null || page < 1){
            page = 1;
        }
        
        Integer pageViewNum = AppConst.DEFAULT_PAGE_VIEW_THREAD_NUMBER();
        if(s != null){
            pageViewNum = s.getPageViewNum();
            if(pageViewNum == null){
                pageViewNum = AppConst.DEFAULT_PAGE_VIEW_THREAD_NUMBER();
            }
        }else{
            s = new Session();
            s.setPageViewNum(pageViewNum);
        }
        

        Integer offset = (page - 1) * pageViewNum;
        Integer limit = page * pageViewNum - 1;
        // スレッドを取得
        IndexService is = new IndexService();
        List<Thread> threads = is.getThreads(offset, limit);
        
        if(threads != null){
            count = threads.size();
        }
        
        requestScope("count", count);
        requestScope("list", threads);
        sessionScope(SessionConst.USER_SESSION_KEY(), s);
        return forward(ForwardUtil.forwardJsp("index.jsp"));
    }
}
